#include "GateSessionManager.h"
#include "GateSessionBase.h"
#include "LogEx.h"
using namespace std;

SINGLETON_CLASS_INIT(CGateSessionManager);
	
void CGateSessionManager::AddGateSession(s32 gateid, CGateSessionBase *gateSession)
{
	if( !gateSession )
	{
		LOG_ERROR( "CGateSessionManager::AddGateSession gateSession is NULL. gateid[%d]", gateid );
		return;
	}

	CGateSessionBase *old = FindGateSession( gateid );
	if( old )
	{
		LOG_ERROR( "CGateSessionManager::AddGateSession aleardy existed gate[%d]", gateid );
	}
	m_gates[ gateid ] = gateSession;
}

void CGateSessionManager::RemoveGateSession(s32 gateid)
{
	map<s32, CGateSessionBase*>::iterator it = m_gates.find( gateid );
	if( it != m_gates.end() )
	{
		m_gates.erase( it );
	}
	else
	{
		LOG_ERROR( "CGateSessionManager::RemoveGateSession failed. not found gate[%d]", gateid );
	}
}

CGateSessionBase* CGateSessionManager::FindGateSession(s32 gateid)
{
	map<s32, CGateSessionBase*>::iterator it = m_gates.find( gateid );
	if( it != m_gates.end() )
	{
		return it->second;
	}
	return NULL;
}

void CGateSessionManager::DumpGateInfo(vector<publicproto::GateStatus> &infos)
{
	map<s32, CGateSessionBase*>::iterator it = m_gates.begin();
	for( ; it != m_gates.end(); ++it )
	{
		if( it->second )
		{
			publicproto::GateStatus info;
			info.gateid = it->first;
			it->second->GetGateState( info.cur_conn, info.max_conn, info.ip, info.port );
			infos.push_back( info );
		}
		else
		{
			LOG_WARN( "CGateSessionManager::DumpGateInfo not found gate[%d]", it->first );
		}
	}
}
